using B.S.RbacData.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.suppliers;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.suppliers
{
    /// <summary>
    /// 更新供应商状态命令处理器
    /// </summary>
    public class UpdateSupplierStatusCommandHandler : IRequestHandler<UpdateSupplierStatusCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<Supplier> _supplierRepository;
        private readonly ILogger<UpdateSupplierStatusCommandHandler> _logger;

        public UpdateSupplierStatusCommandHandler(
            IBaseRepository<Supplier> supplierRepository,
            ILogger<UpdateSupplierStatusCommandHandler> logger)
        {
            _supplierRepository = supplierRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理更新供应商状态命令
        /// </summary>
        /// <param name="request">更新状态命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>操作结果</returns>
        public async Task<ApiResult<bool>> Handle(UpdateSupplierStatusCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始更新供应商状态，ID: {SupplierId}, 新状态: {Status}", 
                    request.Id, request.Status);

                // 检查供应商是否存在且未被删除
                var existingSupplier = await _supplierRepository.GetAll()
                    .FirstOrDefaultAsync(s => s.Id == request.Id && !s.IsDeleted, cancellationToken);

                if (existingSupplier == null)
                {
                    _logger.LogWarning("供应商不存在或已被删除，ID: {SupplierId}", request.Id);
                    return ApiResult<bool>.Error("供应商不存在或已被删除");
                }

                // 验证状态值
                if (request.Status != "启用" && request.Status != "停用")
                {
                    _logger.LogWarning("无效的状态值: {Status}", request.Status);
                    return ApiResult<bool>.Error("状态值无效，只能是'启用'或'停用'");
                }

                // 检查状态是否已经是要设置的状态
                if (existingSupplier.Status == request.Status)
                {
                    _logger.LogWarning("供应商已经是目标状态，ID: {SupplierId}, 当前状态: {CurrentStatus}, 目标状态: {TargetStatus}", 
                        request.Id, existingSupplier.Status, request.Status);
                    return ApiResult<bool>.Error($"供应商已经是{request.Status}状态");
                }

                // 更新状态
                var oldStatus = existingSupplier.Status;
                existingSupplier.Status = request.Status;
                existingSupplier.UpdatedTime = DateTime.Now;
                existingSupplier.UpdatedBy = 1;

              

                // 执行更新操作
                var result = await _supplierRepository.UpdateAsync(existingSupplier);

                if (result > 0)
                {
                    _logger.LogInformation("成功更新供应商状态，ID: {SupplierId}, 名称: {SupplierName}, 状态: {OldStatus} -> {NewStatus}", 
                        request.Id, existingSupplier.SupplierName, oldStatus, request.Status);
                    
                    return ApiResult<bool>.Success(true, $"供应商状态已更新为{request.Status}");
                }
                else
                {
                    _logger.LogError("更新供应商状态失败，ID: {SupplierId}, 名称: {SupplierName}", 
                        request.Id, existingSupplier.SupplierName);
                    
                    return ApiResult<bool>.Error("更新供应商状态失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新供应商状态时发生异常，ID: {SupplierId}, 状态: {Status}", 
                    request.Id, request.Status);
                
                return ApiResult<bool>.Error($"更新供应商状态时发生异常: {ex.Message}");
            }
        }
    }
} 